# views.py
from django.views import View
from django.http import JsonResponse
from pony.orm import db_session
from django.views.decorators.csrf import csrf_exempt
from .models import Person, Car
from django.utils.decorators import method_decorator
import json


@method_decorator(csrf_exempt, name='dispatch')
@method_decorator(db_session, name='dispatch')
class PersonView(View):
    # 列出所有 Person（GET）
    def get(self, request, *args, **kwargs):
        people = Person.select()
        return JsonResponse(
            [{'id': person.id, 'name': person.name, 'age': person.age} for person in people],
            safe=False
        )

    # 创建 Person（POST）
    def post(self, request, *args, **kwargs):
        name = request.POST.get('name')
        age = request.POST.get('age')
        if name and age:
            person = Person(name=name, age=int(age))
            return JsonResponse({'id': person.id, 'name': person.name, 'age': person.age}, status=201)
        return JsonResponse({'error': 'Name and age are required'}, status=400)

    # 更新 Person（PUT）
    def put(self, request, pk, *args, **kwargs):
        data = json.loads(request.body)
        name = data.get('name')
        age = data.get('age')

        person = Person.get(id=pk)
        if person:
            if name:
                person.name = name
            if age:
                person.age = int(age)
            return JsonResponse({'id': person.id, 'name': person.name, 'age': person.age}, status=200)
        return JsonResponse({'error': 'Person not found'}, status=404)

    # 删除 Person（DELETE）
    def delete(self, request, pk, *args, **kwargs):
        person = Person.get(id=pk)
        if person:
            person.delete()
            return JsonResponse({'status': 'deleted'}, status=200)
        return JsonResponse({'error': 'Person not found'}, status=404)


@method_decorator(csrf_exempt, name='dispatch')
@method_decorator(db_session, name='dispatch')
class CarView(View):
    # 列出所有 Car（GET）
    def get(self, request, *args, **kwargs):
        cars = Car.select()
        return JsonResponse(
            [{'id': car.id, 'make': car.make, 'model': car.model, 'owner_id': car.owner.id} for car in cars],
            safe=False
        )

    # 创建 Car（POST）
    def post(self, request, *args, **kwargs):
        person_id = request.POST.get('person_id')
        make = request.POST.get('make')
        model = request.POST.get('model')

        person = Person.get(id=person_id)
        if person:
            car = Car(make=make, model=model, owner=person)
            return JsonResponse({'id': car.id, 'make': car.make, 'model': car.model, 'owner_id': car.owner.id},
                                status=201)
        return JsonResponse({'error': 'Person not found'}, status=404)

    # 更新 Car（PUT）
    def put(self, request, pk, *args, **kwargs):
        data = json.loads(request.body)
        make = data.get('make')
        model = data.get('model')
        person_id = data.get('person_id')
        person = Person.get(id=person_id)

        car = Car.get(id=pk)
        if car:
            if make:
                car.make = make
            if model:
                car.model = model
            if person:
                car.owner=person
            return JsonResponse({'id': car.id, 'make': car.make, 'model': car.model, 'owner': car.owner.name}, status=200)
        return JsonResponse({'error': 'Car not found'}, status=404)

    # 删除 Car（DELETE）
    def delete(self, request, pk, *args, **kwargs):
        car = Car.get(id=pk)
        if car:
            car.delete()
            return JsonResponse({'status': 'deleted'}, status=200)
        return JsonResponse({'error': 'Car not found'}, status=404)

